package cn.codergege.demo.controller;

import cn.codergege.demo.dao.DepartmentRepository;
import cn.codergege.demo.domain.Department;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/chpt2")
public class Chpt2Controller {
    private final Logger log = LoggerFactory.getLogger(Chpt2Controller.class); 
    
    @Autowired
    private DepartmentRepository departmentRepository;

    /****************************************
    |              C
    ****************************************/
    @RequestMapping("/dept")
    public String addDept(Map<String, Object> map) {
        Department department = new Department();
        map.put("department", department);
        return "chpt2/add-dept";
    }

    @RequestMapping(value = "/dept", method = RequestMethod.POST)
    public String addDept(@Valid Department department, BindingResult error, Map<String, Object> map) {
        System.out.println("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
        System.out.println("错误数量: " + error.getErrorCount());
        System.out.println("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
        if(error.hasErrors()) {
            log.info("保存部门出错, 有不符合要求的字段: " + error.getFieldErrors().toString());
            return "chpt2/add-dept";
        }
        departmentRepository.add(department);
        return "redirect:/chpt2/depts";
    }

    /****************************************
    |              R
    ****************************************/

    @RequestMapping("/view-a-dept/{id}")
    public String viewadept(@PathVariable("id") Integer id, Map<String, Object> map) {
        Department department = departmentRepository.getDepartmentById(id);
        map.put("department", department);
        return "chpt2/view-a-dept";
    }

    @RequestMapping("/depts")
    public String depts(Map<String, Object> map) {
        List<Department> departments = departmentRepository.findAll();
        map.put("departments", departments);
        return "chpt2/depts";
    }
}
